<?php

namespace App\Http\Controllers\Api;

use App\BooksChapter;
use App\BooksInfo;
use App\Distribution;
use App\Exceptions\OrderException;
use App\Exceptions\PaymentException;
use App\Http\Services\UserManager;
use App\Orders;
use App\RechargePackage;
use App\User;
use App\UserBalanceRecord;
use App\UserBooks;
use App\UserInfo;
use App\UserSpendRecord;
use App\UserVip;
use App\VipRule;
use App\Withdraw;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class PaymentController extends Controller
{
    /**
     * 微信支付接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws OrderException
     * @throws PaymentException
     */
    public function weChatPayment(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->whereUserId($user->id)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($thisOrder->type == 'company_payment')
            return response()->json(['level' => 'error','message' => '订单类型不正确']);

        if($thisOrder->is_pay == 1)
            return response()->json(['level' => 'error','message' => '订单已支付']);

        if($thisOrder->type == 'vip'){
            /** @var VipRule $thisVipRule */
            $thisVipRule = VipRule::whereId($thisOrder->vip_rule_id)->first();
            if(!$thisVipRule)
                return response()->json(['level' => 'error','message' => '会员套餐不存在！']);

            $thisUserVip = UserVip::whereUserId($thisOrder->user_id)->whereType($thisVipRule->type)->whereClassifyId($thisVipRule->classify_id)->whereEndTime('00-00-00 00:00:00')->first();
            if($thisUserVip)
                return response()->json(['level' => 'error','message' => '您已经购买永久期限了，无需重复购买']);
        }

        $config = [
            // 必要配置
            'app_id'             => 'wx4457b4ba6dfdf545',
            'mch_id'             => '1523831651',
            'key'                => 'd7bd3640f43c5d3113c3c4597e1d08b2',   // API 密钥
        ];

        $app = Factory::payment($config);

        $result = $app->order->unify([
            'body' => '读物购买',
            'out_trade_no' => $thisOrder->order_num,
            'total_fee' => (float)$thisOrder->amount_money * 100,
            'spbill_create_ip' => '', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => route('Api.Payment.WeChatPayCallback'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->wx_openid,
        ]);

        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $jssdk = $app->jssdk;
            $prepayId = $result['prepay_id'];
            $json = $jssdk->bridgeConfig($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false

            return response()->json(['level' => 'success','message' => '订单创建成功','data'=>json_decode($json)]);
        }else{
            return response()->json(['level' => 'error','message' => '订单创建失败','data' => $result]);
        }
    }

    /**
     * 读物购买接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws OrderException
     * @throws PaymentException
     */
    public function booksBuy(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($thisOrder->is_pay == 1)
            return response()->json(['level' => 'error','message' => '订单已支付']);


        if($thisOrder->type == 'book'){
            /** @var BooksInfo $thisBooksInfo */
            $thisBooksInfo = BooksInfo::whereId($thisOrder->books_id)->whereStatus(1)->first();
            if($thisBooksInfo){
                /** @var User $thisUser */
                $thisUser = User::whereId($thisOrder->user_id)->first();
                if($thisUser){
                    /** @var UserInfo $thisUserInfo */
                    $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                    if($thisUserInfo){
                        //判断用户账户中的阅读币数量是小于订单中的阅读币数量
                        if($thisOrder->amount_books_coin > $thisUserInfo->books_coin)
                            return response()->json(['level' => 'error','message' => '账户内阅读币数量不足']);

                        /** @var UserBooks $isUserCollectBooks */
                        $isUserCollectBooks = UserBooks::whereUserId($thisUserInfo->user_id)->whereBooksInfoId($thisBooksInfo->id)->first();
                        if($isUserCollectBooks)
                            return response()->json(['level' => 'error','message' => '您已经购买过该读物了，无需重复购买']);

                        //减去用户账户中的阅读币
                        $minusBooksCoin = $thisUserInfo->books_coin - $thisOrder->amount_books_coin;
                        $thisUserInfo->books_coin = $minusBooksCoin;
                        $thisUserInfo->save();

                        $newUserBooks = new UserBooks();
                        $newUserBooks->user_id       = $thisUserInfo->user_id;
                        $newUserBooks->books_info_id = $thisBooksInfo->id;
                        $newUserBooks->save();

                        $thisOrder->pay_time = date('Y-m-d H:i:s',time());
                        $thisOrder->pay_type = 'books_coin';
                        $thisOrder->is_pay   = 1;
                        $thisOrder->status   = 1;
                        $thisOrder->save();

                        $newUserOPendRecord = new UserSpendRecord();
                        $newUserOPendRecord->user_id = $thisOrder->user_id;
                        $newUserOPendRecord->order_num = $thisOrder->order_num;
                        $newUserOPendRecord->books_id = $thisOrder->books_id;
                        $newUserOPendRecord->num = $thisOrder->num;
                        $newUserOPendRecord->amount_books_coin = $thisOrder->amount_books_coin;
                        $newUserOPendRecord->type = $thisOrder->type;
                        $newUserOPendRecord->is_pay = $thisOrder->is_pay;
                        $newUserOPendRecord->pay_time = $thisOrder->pay_time;
                        $newUserOPendRecord->pay_type = $thisOrder->pay_type;
                        $newUserOPendRecord->save();
                    }else{
                        return response()->json(['level' => 'error','message' => '用户信息不存在']);
                    }
                }else{
                    return response()->json(['level' => 'error','message' => '用户不存在']);
                }
            }else{
                return response()->json(['level' => 'error','message' => '购买的读物已下架']);
            }
        }elseif($thisOrder->type == 'book_chapter'){
            /** @var BooksChapter $thisBooksChapter */
            $thisBooksChapter = BooksChapter::whereId($thisOrder->books_id)->whereStatus(1)->first();
            if($thisBooksChapter){
                /** @var BooksInfo $thisBooksInfo */
                $thisBooksInfo = BooksInfo::whereId($thisBooksChapter->books_info_id)->whereStatus(1)->first();
                if(!$thisBooksInfo)
                    return response()->json(['level' => 'error','message' => '该章节所属的书已下架']);

                /** @var User $thisUser */
                $thisUser = User::whereId($thisOrder->user_id)->first();
                if($thisUser){
                    /** @var UserInfo $thisUserInfo */
                    $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                    if($thisUserInfo){
                        //判断用户账户中的阅读币数量是小于订单中的阅读币数量
                        if($thisOrder->amount_books_coin > $thisUserInfo->books_coin)
                            return response()->json(['level' => 'error','message' => '账户内阅读币数量不足']);

                        /** @var UserBooks $isUserCollectBooks */
                        $isUserCollectBooks = UserBooks::whereUserId($thisUserInfo->user_id)->whereBooksInfoId($thisBooksInfo->id)->whereBooksChapterId(0)->first();
                        if($isUserCollectBooks)
                            return response()->json(['level' => 'error','message' => '您已经购买过该读物了，无需重复购买']);


                        /** @var UserBooks $isUserCollectBooks */
                        $isUserCollectBooksChapter = UserBooks::whereUserId($thisUserInfo->user_id)->whereBooksInfoId($thisBooksInfo->id)->whereBooksChapterId($thisBooksChapter->id)->first();
                        if($isUserCollectBooksChapter)
                            return response()->json(['level' => 'error','message' => '您已经购买过该章节了，无需重复购买']);

                        //减去用户账户中的阅读币
                        $minusBooksCoin = $thisUserInfo->books_coin - $thisOrder->amount_books_coin;
                        $thisUserInfo->books_coin = $minusBooksCoin;
                        $thisUserInfo->save();

                        $newUserBooks = new UserBooks();
                        $newUserBooks->user_id          = $thisUserInfo->user_id;
                        $newUserBooks->books_info_id    = $thisBooksInfo->id;
                        $newUserBooks->books_chapter_id = $thisBooksChapter->id;
                        $newUserBooks->save();

                        $thisOrder->pay_time = date('Y-m-d H:i:s',time());
                        $thisOrder->pay_type = 'books_coin';
                        $thisOrder->is_pay   = 1;
                        $thisOrder->status   = 1;
                        $thisOrder->save();

                        $newUserOPendRecord = new UserSpendRecord();
                        $newUserOPendRecord->user_id = $thisOrder->user_id;
                        $newUserOPendRecord->order_num = $thisOrder->order_num;
                        $newUserOPendRecord->books_id = $thisOrder->books_id;
                        $newUserOPendRecord->num = $thisOrder->num;
                        $newUserOPendRecord->amount_books_coin = $thisOrder->amount_books_coin;
                        $newUserOPendRecord->type = $thisOrder->type;
                        $newUserOPendRecord->is_pay = $thisOrder->is_pay;
                        $newUserOPendRecord->pay_time = $thisOrder->pay_time;
                        $newUserOPendRecord->pay_type = $thisOrder->pay_type;
                        $newUserOPendRecord->save();
                    }else{
                        return response()->json(['level' => 'error','message' => '用户信息不存在']);
                    }
                }else{
                    return response()->json(['level' => 'error','message' => '用户不存在']);
                }
            }else{
                return response()->json(['level' => 'error','message' => '购买的章节已下架']);
            }
        }else{
            return response()->json(['level' => 'error','message' => '订单类型不正确']);
        }

        return response()->json(['level' => 'success','message' => '购买成功','data' => $thisOrder]);
    }

    //微信支付回调
    public function WeChatPayCallback(Request $request){
        $config = [
            // 必要配置
            'app_id'             => 'wx4457b4ba6dfdf545',
            'mch_id'             => '1523831651',
            'key'                => 'd7bd3640f43c5d3113c3c4597e1d08b2',   // API 密钥
        ];

        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            $ordersNum = $message['out_trade_no'];

            /** @var Orders $order */
            $order = Orders::whereOrderNum($ordersNum)->first();

            if(!$order || ($order && $order->is_pay == 1)){
                return true;
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->pay_time = date('Y-m-d H:i:s',time()); // 更新支付时间为当前时间
                    $order->pay_type = 'wechat';
                    $order->is_pay   = 1;

                if($order->type == 'books_coin'){
                    /** @var RechargePackage $thisRechargePackage */
                    $thisRechargePackage = RechargePackage::whereId($order->recharge_package_id)->first();
                    if($thisRechargePackage){
                        /** @var User $thisUser */
                        $thisUser = User::whereId($order->user_id)->first();
                        if($thisUser){
                            /** @var UserInfo $thisUserInfo */
                            $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                            if($thisUserInfo){
                                $thisUserInfo->books_coin = $thisUserInfo->books_coin + $thisRechargePackage->books_coin + $thisRechargePackage->gift_books_coin;
                                $thisUserInfo->save();

                                /** @var Distribution $thisDistribution */
                                $thisDistribution = Distribution::whereSecondaryUserId($thisUserInfo->id)->first();
                                if($thisDistribution){
                                    /** @var UserInfo $thisFirstUserInfo */
                                    $thisFirstUserInfo = UserInfo::whereUserId($thisDistribution->first_user_id)->first();
                                    if($thisFirstUserInfo){
                                        $thisFirstUserInfo->balance = $thisFirstUserInfo->balance + ($order->amount_money * 0.05);
                                        $thisFirstUserInfo->save();

                                        $newUserBalanceRecord = new UserBalanceRecord();
                                        $newUserBalanceRecord->user_id           = $thisFirstUserInfo->user_id;
                                        $newUserBalanceRecord->order_num         = $order->order_num;
                                        $newUserBalanceRecord->secondary_user_id = $thisUser->id;
                                        $newUserBalanceRecord->income_balance    = $order->amount_money * 0.05;
                                        $newUserBalanceRecord->save();
                                    }
                                }

                                $newUserOPendRecord = new UserSpendRecord();
                                $newUserOPendRecord->user_id                 = $order->user_id;
                                $newUserOPendRecord->order_num               = $order->order_num;
                                $newUserOPendRecord->recharge_package_id     = $order->recharge_package_id;
                                $newUserOPendRecord->num                     = $order->num;
                                $newUserOPendRecord->amount_money            = $order->amount_money;
                                $newUserOPendRecord->type                    = $order->type;
                                $newUserOPendRecord->is_pay                  = $order->is_pay;
                                $newUserOPendRecord->pay_time                = $order->pay_time;
                                $newUserOPendRecord->pay_type                = $order->pay_type;
                                $newUserOPendRecord->save();
                            }else{
                                 return response()->json(['level' => 'error','message' => '用户信息不存在']);
                            }
                        }else{
                            return response()->json(['level' => 'error','message' => '用户不存在!']);
                        }
                    }else{
                        return response()->json(['level' => 'error','message' => '充值套餐不存在!']);
                    }
                }elseif($order->type == 'vip'){
                    /** @var VipRule $thisVipRule */
                    $thisVipRule = VipRule::whereId($order->vip_rule_id)->first();
                    if(!$thisVipRule)
                        return response()->json(['level' => 'error','message' => '会员套餐不存在！']);

                    /** @var User $thisUser */
                    $thisUser = User::whereId($order->user_id)->first();
                    if($thisUser){
                        if($thisVipRule->type == 'global_vip'){
                            /** @var UserVip $thisUserIVip */
                            $thisUserIVip = UserVip::whereUserId($thisUser->id)->whereType('global_vip')->first();
                            if(!$thisUserIVip){
                                $thisUserIVip = new UserVip();
                                $thisUserIVip->user_id         = $thisUser->id;
                                $thisUserIVip->start_time      = date('Y-m-d H:i:s',time());
                                $thisUserIVip->end_time        = $thisVipRule->vip_time == -1 ? "0000-00-00 00:00:00" : date('Y-m-d H:i:s',time() + ($thisVipRule->vip_time * 24 * 3600));
                                $thisUserIVip->type            = $thisVipRule->type;
                                $thisUserIVip->classify_id     = $thisVipRule->classify_id;
                                $thisUserIVip->status          = 1;
                                $thisUserIVip->save();

                                /** @var UserInfo $thisUserInfo */
                                $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                                if(!$thisUserInfo)
                                    return response()->json(['level' => 'error','message' => '用户信息不存在']);

                                /** @var Distribution $thisDistribution */
                                $thisDistribution = Distribution::whereSecondaryUserId($thisUser->id)->first();
                                if($thisDistribution){
                                    /** @var UserInfo $thisFirstUserInfo */
                                    $thisFirstUserInfo = UserInfo::whereUserId($thisDistribution->first_user_id)->first();
                                    if($thisFirstUserInfo){
                                        $thisFirstUserInfo->balance = $thisFirstUserInfo->balance + ($order->amount_money * 0.05);
                                        $thisFirstUserInfo->save();

                                        $newUserBalanceRecord = new UserBalanceRecord();
                                        $newUserBalanceRecord->user_id           = $thisFirstUserInfo->user_id;
                                        $newUserBalanceRecord->order_num         = $order->order_num;
                                        $newUserBalanceRecord->secondary_user_id = $thisUser->id;
                                        $newUserBalanceRecord->income_balance    = $order->amount_money * 0.05;
                                        $newUserBalanceRecord->save();
                                    }
                                }

                                $newUserOPendRecord = new UserSpendRecord();
                                $newUserOPendRecord->user_id         = $order->user_id;
                                $newUserOPendRecord->order_num       = $order->order_num;
                                $newUserOPendRecord->vip_rule_id     = $order->vip_rule_id;
                                $newUserOPendRecord->num             = $order->num;
                                $newUserOPendRecord->amount_money    = $order->amount_money;
                                $newUserOPendRecord->type            = $order->type;
                                $newUserOPendRecord->is_pay          = $order->is_pay;
                                $newUserOPendRecord->pay_time        = $order->pay_time;
                                $newUserOPendRecord->pay_type        = $order->pay_type;
                                $newUserOPendRecord->save();
                            }else{
                                if(strtotime($thisUserIVip->end_time) < time()){
                                    $thisUserIVip->user_id         = $thisUser->id;
                                    $thisUserIVip->start_time      = date('Y-m-d H:i:s',time());
                                    $thisUserIVip->end_time        = $thisVipRule->vip_time == -1 ? "0000-00-00 00:00:00" : date('Y-m-d H:i:s',time() + ($thisVipRule->vip_time * 24 * 3600));
                                    $thisUserIVip->type            = $thisVipRule->type;
                                    $thisUserIVip->classify_id     = $thisVipRule->classify_id;
                                    $thisUserIVip->status          = 1;
                                    $thisUserIVip->save();
                                }else{
                                    $thisUserIVip->user_id         = $thisUser->id;
                                    $thisUserIVip->end_time        = $thisVipRule->vip_time == -1 ? "0000-00-00 00:00:00" : date('Y-m-d H:i:s',strtotime($thisUserIVip->end_time) + ($thisVipRule->vip_time * 24 * 3600));
                                    $thisUserIVip->type            = $thisVipRule->type;
                                    $thisUserIVip->classify_id     = $thisVipRule->classify_id;
                                    $thisUserIVip->status          = 1;
                                    $thisUserIVip->save();
                                }

                                /** @var UserInfo $thisUserInfo */
                                $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                                if(!$thisUserInfo)
                                    return response()->json(['level' => 'error','message' => '用户信息不存在']);

                                /** @var Distribution $thisDistribution */
                                $thisDistribution = Distribution::whereSecondaryUserId($thisUser->id)->first();
                                if($thisDistribution){
                                    /** @var UserInfo $thisFirstUserInfo */
                                    $thisFirstUserInfo = UserInfo::whereUserId($thisDistribution->first_user_id)->first();
                                    if($thisFirstUserInfo){
                                        $thisFirstUserInfo->balance = $thisFirstUserInfo->balance + ($order->amount_money * 0.05);
                                        $thisFirstUserInfo->save();

                                        $newUserBalanceRecord = new UserBalanceRecord();
                                        $newUserBalanceRecord->user_id           = $thisFirstUserInfo->user_id;
                                        $newUserBalanceRecord->order_num         = $order->order_num;
                                        $newUserBalanceRecord->secondary_user_id = $thisUser->id;
                                        $newUserBalanceRecord->income_balance    = $order->amount_money * 0.05;
                                        $newUserBalanceRecord->save();
                                    }
                                }

                                $newUserOPendRecord = new UserSpendRecord();
                                $newUserOPendRecord->user_id         = $order->user_id;
                                $newUserOPendRecord->order_num       = $order->order_num;
                                $newUserOPendRecord->vip_rule_id     = $order->vip_rule_id;
                                $newUserOPendRecord->num             = $order->num;
                                $newUserOPendRecord->amount_money    = $order->amount_money;
                                $newUserOPendRecord->type            = $order->type;
                                $newUserOPendRecord->is_pay          = $order->is_pay;
                                $newUserOPendRecord->pay_time        = $order->pay_time;
                                $newUserOPendRecord->pay_type        = $order->pay_type;
                                $newUserOPendRecord->save();
                            }
                        }elseif($thisVipRule->type == 'classify_vip'){
                            /** @var UserVip $thisUserIVip */
                            $thisUserIVip = UserVip::whereUserId($thisUser->id)->whereType('classify_vip')->whereClassifyId($thisVipRule->classify_id)->first();
                            if(!$thisUserIVip){
                                $thisUserIVip = new UserVip();
                                $thisUserIVip->user_id         = $thisUser->id;
                                $thisUserIVip->start_time      = date('Y-m-d H:i:s',time());
                                $thisUserIVip->end_time        = $thisVipRule->vip_time == -1 ? "0000-00-00 00:00:00" : date('Y-m-d H:i:s',time() + ($thisVipRule->vip_time * 24 * 3600));
                                $thisUserIVip->type            = $thisVipRule->type;
                                $thisUserIVip->classify_id     = $thisVipRule->classify_id;
                                $thisUserIVip->status          = 1;
                                $thisUserIVip->save();

                                /** @var UserInfo $thisUserInfo */
                                $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                                if(!$thisUserInfo)
                                    return response()->json(['level' => 'error','message' => '用户信息不存在']);

                                /** @var Distribution $thisDistribution */
                                $thisDistribution = Distribution::whereSecondaryUserId($thisUser->id)->first();
                                if($thisDistribution){
                                    /** @var UserInfo $thisFirstUserInfo */
                                    $thisFirstUserInfo = UserInfo::whereUserId($thisDistribution->first_user_id)->first();
                                    if($thisFirstUserInfo){
                                        $thisFirstUserInfo->balance = $thisFirstUserInfo->balance + ($order->amount_money * 0.05);
                                        $thisFirstUserInfo->save();

                                        $newUserBalanceRecord = new UserBalanceRecord();
                                        $newUserBalanceRecord->user_id           = $thisFirstUserInfo->user_id;
                                        $newUserBalanceRecord->order_num         = $order->order_num;
                                        $newUserBalanceRecord->secondary_user_id = $thisUser->id;
                                        $newUserBalanceRecord->income_balance    = $order->amount_money * 0.05;
                                        $newUserBalanceRecord->save();
                                    }
                                }

                                $newUserOPendRecord = new UserSpendRecord();
                                $newUserOPendRecord->user_id         = $order->user_id;
                                $newUserOPendRecord->order_num       = $order->order_num;
                                $newUserOPendRecord->vip_rule_id     = $order->vip_rule_id;
                                $newUserOPendRecord->num             = $order->num;
                                $newUserOPendRecord->amount_money    = $order->amount_money;
                                $newUserOPendRecord->type            = $order->type;
                                $newUserOPendRecord->is_pay          = $order->is_pay;
                                $newUserOPendRecord->pay_time        = $order->pay_time;
                                $newUserOPendRecord->pay_type        = $order->pay_type;
                                $newUserOPendRecord->save();
                            }else{
                                if(strtotime($thisUserIVip->end_time) < time()){
                                    $thisUserIVip->user_id         = $thisUser->id;
                                    $thisUserIVip->start_time      = date('Y-m-d H:i:s',time());
                                    $thisUserIVip->end_time        = $thisVipRule->vip_time == -1 ? "0000-00-00 00:00:00" : date('Y-m-d H:i:s',time() + ($thisVipRule->vip_time * 24 * 3600));
                                    $thisUserIVip->type            = $thisVipRule->type;
                                    $thisUserIVip->classify_id     = $thisVipRule->classify_id;
                                    $thisUserIVip->status          = 1;
                                    $thisUserIVip->save();
                                }else{
                                    $thisUserIVip->user_id         = $thisUser->id;
                                    $thisUserIVip->end_time        = $thisVipRule->vip_time == -1 ? "0000-00-00 00:00:00" : date('Y-m-d H:i:s',strtotime($thisUserIVip->end_time) + ($thisVipRule->vip_time * 24 * 3600));
                                    $thisUserIVip->type            = $thisVipRule->type;
                                    $thisUserIVip->classify_id     = $thisVipRule->classify_id;
                                    $thisUserIVip->status          = 1;
                                    $thisUserIVip->save();
                                }

                                /** @var UserInfo $thisUserInfo */
                                $thisUserInfo = UserInfo::whereUserId($thisUser->id)->first();
                                if(!$thisUserInfo)
                                    return response()->json(['level' => 'error','message' => '用户信息不存在']);

                                /** @var Distribution $thisDistribution */
                                $thisDistribution = Distribution::whereSecondaryUserId($thisUser->id)->first();
                                if($thisDistribution){
                                    /** @var UserInfo $thisFirstUserInfo */
                                    $thisFirstUserInfo = UserInfo::whereUserId($thisDistribution->first_user_id)->first();
                                    if($thisFirstUserInfo){
                                        $thisFirstUserInfo->balance = $thisFirstUserInfo->balance + ($order->amount_money * 0.05);
                                        $thisFirstUserInfo->save();

                                        $newUserBalanceRecord = new UserBalanceRecord();
                                        $newUserBalanceRecord->user_id           = $thisFirstUserInfo->user_id;
                                        $newUserBalanceRecord->order_num         = $order->order_num;
                                        $newUserBalanceRecord->secondary_user_id = $thisUser->id;
                                        $newUserBalanceRecord->income_balance    = $order->amount_money * 0.05;
                                        $newUserBalanceRecord->save();
                                    }
                                }

                                $newUserOPendRecord = new UserSpendRecord();
                                $newUserOPendRecord->user_id         = $order->user_id;
                                $newUserOPendRecord->order_num       = $order->order_num;
                                $newUserOPendRecord->vip_rule_id     = $order->vip_rule_id;
                                $newUserOPendRecord->num             = $order->num;
                                $newUserOPendRecord->amount_money    = $order->amount_money;
                                $newUserOPendRecord->type            = $order->type;
                                $newUserOPendRecord->is_pay          = $order->is_pay;
                                $newUserOPendRecord->pay_time        = $order->pay_time;
                                $newUserOPendRecord->pay_type        = $order->pay_type;
                                $newUserOPendRecord->save();
                            }

                        }else{
                            return response()->json(['level' => 'error','message' => '系统错误!']);
                        }
                    }else{
                        return response()->json(['level' => 'error','message' => '用户不存在!']);
                    }
                }else{
                    return response()->json(['level' => 'error','message' => '订单类型不正确!']);
                }

                $order->status   = 1;
                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save(); // 保存订单

            return true; // 返回处理完成

        });

        return $response;
    }

    public function WxCompanyPayment(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->whereUserId($user->id)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($thisOrder->type != 'company_payment')
            return response()->json(['level' => 'error','message' => '订单类型不正确']);

        if($thisOrder->is_pay == 1)
            return response()->json(['level' => 'error','message' => '订单已支付']);

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = UserInfo::whereUserId($user->id)->first();
        if(!$thisUserInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        if($thisUserInfo->balance < $thisOrder->withdraw_money)
            return response()->json(['level' => 'error','message' => '用户余额不足']);

        $config = [
            // 必要配置
            'app_id'             => 'wx5933cfbdf4440b1f',
            'mch_id'             => '1499372402',
            'key'                => 'cd758e5bcc53a80c2329acbabeb8a20a',   // API 密钥  寿哥的key：75c4c90030ef6504a4e309f08f91090d

            'cert_path'          => base_path().'/public/apiclient_cert.pem',
            'key_path'           => base_path().'/public/apiclient_key.pem',
        ];

        $app = Factory::payment($config);

        $result = $app->transfer->toBalance([
            'partner_trade_no' => $thisOrder->order_num, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $user->wx_openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => (float)$thisOrder->withdraw_money * 100, // 企业付款金额，单位为分
            'desc' => '用户提现', // 企业付款操作说明信息。必填
        ]);

        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            if($result['payment_no']){
                /** @var Orders $thisOrder */
                $thisOrder = Orders::whereOrderNum($result['partner_trade_no'])->first();
                if(!$thisOrder)
                    return response()->json(['level' => 'error','message' => '订单不存在']);

                $thisUserInfo = UserInfo::whereUserId($thisOrder->user_id)->first();
                if(!$thisUserInfo)
                    return response()->json(['level' => 'error','message' => '用户信息不存在']);

                if($thisOrder->type != 'company_payment')
                    return response()->json(['level' => 'error','message' => '订单类型不正确']);

                if($thisOrder->is_pay == 1)
                    return response()->json(['level' => 'error','message' => '订单已支付']);

                $thisOrder->is_pay     = 1;
                $thisOrder->pay_time   = $result['payment_time'];
                $thisOrder->pay_type   = 'wechat';
                $thisOrder->status     = 1;

                /** @var Withdraw $thisWithdraw */
                $thisWithdraw = Withdraw::whereOrderNum($thisOrder->order_num)->whereUserId($user->id)->first();
                if($thisWithdraw){
                    $thisWithdraw->status = 1;
                    $thisWithdraw->save();
                }else{
                    return response()->json(['level' => 'error','message' => '系统错误']);
                }

                $thisUserInfo->balance = $thisUserInfo->balance - $thisWithdraw->amount;
                $thisUserInfo->save();

                return response()->json(['level' => 'success','message' => '提现成功','data' => $result]);
            }else{
                /** @var Withdraw $thisWithdraw */
                $thisWithdraw = Withdraw::whereOrderNum($thisOrder->order_num)->whereUserId($user->id)->first();
                if($thisWithdraw){
                    $thisWithdraw->status = 0;
                    $thisWithdraw->reason = isset($result['err_code_des']) ? $result['err_code_des'] : '提现失败';
                    $thisWithdraw->save();
                }else{
                    return response()->json(['level' => 'error','message' => '系统错误']);
                }

                return response()->json(['level' => 'error','message' => '提现失败','data' => $result]);
            }
        }else{
            /** @var Withdraw $thisWithdraw */
            $thisWithdraw = Withdraw::whereOrderNum($thisOrder->order_num)->whereUserId($user->id)->first();
            if($thisWithdraw){
                $thisWithdraw->status = 0;
                $thisWithdraw->reason = isset($result['err_code_des']) ? $result['err_code_des'] : '提现失败';
                $thisWithdraw->save();
            }else{
                return response()->json(['level' => 'error','message' => '系统错误']);
            }

            return response()->json(['level' => 'error','message' => '提现失败','data' => $result]);
        }
    }
}
